<template>
  <el-row class="set-box">
    <el-form
      label-width="120px"
      :model="form"
      ref="form"
      v-bind="getFormProps()">
      <div
        :submit="1"
        disabled
        :form.sync="item"
        :formkey="index"
        v-for="(item,index) in form.rightsDetailList"
        :key="index">
        <div class="form-style">
          <div class="set-colse" v-if="index!=0">
            <el-button type="text" icon="close" @click="form.rightsDetailList.splice(index, 1)"></el-button>
          </div>
          <el-form-item label="权益名称："
              :prop="`rightsDetailList.${index}.rightsName`"
              :rules="[
                { required: true, message: '权益名称不能为空'},
              ]">
            <el-col :span="18">
              <el-input v-model="item.rightsName" placeholder="请输入权益名称" :maxlength="40" number-word />
            </el-col>
          </el-form-item>
          <el-form-item
            label="权益类型："
            :prop="`rightsDetailList.${index}.rightsTypeCode`"
            :rules="{ required: true, message: '请选择权益类型'}">
            <el-col :span="18">
              <el-select v-model="item.rightsTypeCode" placeholder="请选择权益类型">
              <el-option
                v-for="(item,index) in dict.equitysTypes.data"
                :value="item.value"
                :label="item.label"
                :key="index">
              </el-option>
            </el-select>
            </el-col>
          </el-form-item>
          <el-form-item
            label="行业排他："
            :prop="`rightsDetailList.${index}.exclusiveStatus`"
              :rules="[
                { required: true, message: '行业排他不能为空'},
              ]">
            <el-col :span="20">
              <el-radio-group v-model="item.exclusiveStatus">
                <el-radio v-for="(item,index) in dict.yesNo.data" :key="index" :label="item.value">{{item.label}}</el-radio>
              </el-radio-group>
            </el-col>
          </el-form-item>
          <el-form-item
            label="赞助方式："
            :prop="`rightsDetailList.${index}.sponsorType`"
            :rules="{ required: true, message: '请选择赞助方式'}">
            <el-col :span="18">
              <el-select v-model="item.sponsorType" placeholder="请选择赞助方式">
              <el-option v-for="(item,index) in dict.sponsorTypes.data" :value="item.value" :label="item.label" :key="index"></el-option>
            </el-select>
            </el-col>
          </el-form-item>
          <el-form-item
            v-if="form.rightsDetailList[index].sponsorType === 1 || form.rightsDetailList[index].sponsorType === 3"
            label="现金赞助："
            :prop="`rightsDetailList.${index}.investmentAmount`"
            :rules="[
              { required: true, message: '金额不能为空'},
              Object.assign({}, validator.rule.isIntadd,{message: '输入格式不正确，金额为正整数'})
            ]">
            <el-col :span="18">
              <el-input type="text" :maxlength="11" placeholder="请输入招商金额" v-model="item.investmentAmount">
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item
            v-if="form.rightsDetailList[index].sponsorType === 2 || form.rightsDetailList[index].sponsorType === 3"
            label="物品金额："
            :prop="`rightsDetailList.${index}.realPrice`"
            :rules="[
              { required: true, message: '金额不能为空'},
              Object.assign({}, validator.rule.isIntadd,{message: '输入格式不正确，金额为正整数'})
            ]">
            <el-col :span="18">
              <el-input type="text" :maxlength="11" placeholder="请输入物品金额" v-model="item.realPrice">
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="权益内容："
            :prop="`rightsDetailList.${index}.rightsDetails`"
            :rules="[
              {required: true, message: '内容不能为空'},
              Object.assign({message: '内容不能为空'}, validator.rule.emptyArray)
            ]">
            <el-col :span="20">
              <e-input-group
                type="textarea"
                :minRows="4"
                :minlength="2"
                :maxlength="300"
                :max-item="8"
                number-word
                placeholder="请输入权益内容"
                v-model="item.rightsDetails">
              </e-input-group>
            </el-col>
          </el-form-item>
        </div>
        <div class="set-button-box">
          <el-button class="btn-icon" icon="plus" @click="addFormItem()" v-if="index==form.rightsDetailList.length-1 && form.rightsDetailList.length < 10"></el-button>
        </div>
      </div>
    </el-form>
    <div class="button-box">
      <el-button type="default" @click="prev()" v-if="!id">上一步</el-button>
      <el-button type="primary" @click="next()" v-if="!id">下一步</el-button>
      <el-button type="primary" :loading="loading" native-type="submit" v-if="id" @click="save()">保存</el-button> 
    </div>
  </el-row>
</template>
<script>
import { mapGetters } from 'vuex'
import EInputGroup from '@e-ui/InputGroup'
import EquityGroup from '../components/EquityGroup'
import Equity from '../components/Equity'
import {form} from 'utils/mixins'
import validator from '../../../utils/validator'
import api from 'api/merchants'
export default {
  props: {
    activeChange: {
      type: Function
    }
  },
  mixins: [form],
  components: {
    EInputGroup,
    EquityGroup,
    Equity
  },
  computed: {
    ...mapGetters({
      dict: 'merchants_dict',
      form: 'merchants_form'
    })
  },
  data () {
    return {
      validator,
      loading: false,
      id: this.$route.params.id,
      equitys: [
        {
          value: 0,
          label: '冠名权益'
        },
        {
          value: 1,
          label: '合作伙伴'
        }
      ],
      setData: {
        rightsDetailList: [{
          rightsName: '',
          rightsTypeCode: '',
          exclusiveStatus: 1,
          sponsorType: '',
          rightsDetails: []
        }]
      }
    }
  },
  created () {
    this.activeChange(2)
    if (this.form.rightsDetailList.length === 0) {
      this.addFormItem()
    }
  },
  methods: {
    save () {
      let setdata = Object.assign({}, this.setData)
      let formdata = Object.assign({}, this.form)
      for (var attr in setdata) { // 将返回来的数据做跟我的form里面的数据要一一对应进来，只拿form所需要的数据
        setdata[attr] = formdata[attr]
      }
      for (let item of setdata.rightsDetailList) {
        if (item.sponsorType === 1) { // 如果只选了现金的话，那么实物价格为0
          item.realPrice = 0
        } else if (item.sponsorType === 2) { // 如果只选了物质的话，那么现金价格为0
          item.investmentAmount = 0
        }
      }
      setdata.rightsDetailList = setdata.rightsDetailList.map(function (item) {
        return {
          exclusiveStatus: item.exclusiveStatus, // 是否排他：0否 ，1是
          investmentAmount: parseInt(item.investmentAmount) * 100, // 招商金额/现金赞助（单位：分） 将单位元转换成分
          realPrice: parseInt(item.realPrice) * 100, // 实物总价/物品赞助 (单位：分) 将单位元转换成分
          rightsDetails: item.rightsDetails, // 子权益列表
          rightsName: item.rightsName, // 权益名称
          rightsTypeCode: item.rightsTypeCode, // 权益类型
          sponsorType: item.sponsorType // 赞助类型/方式
        }
      })
      // console.log(setdata, 'setdata')
      // console.log(formdata, 'formdata')
      // console.log(this.form, 'this.form')
      setdata.id = this.id
      this.$refs['form'].validate((valid) => { // 验证通过提交保存
        if (valid) {
          api.rights_update(JSON.stringify(setdata), {context: this, successMsg: 'none'}).then((json) => {
            this.$message.success('修改成功')
          }).catch(() => {
            this.$message.warning('服务器繁忙，请稍后再试！')
          })
        } else {
          this.$message.warning('请输入完整信息')
          return false
        }
      })
    },
    prev () {
      this.$store.commit('SPONSOR_MERCHANTS_COOKIES') // 刷新页面时，点击上一步的时候，拿到cookies值赋值给this.form
      this.$router.push({path: '/sponsor/merchants/add'})
    },
    next () {
      this.$store.commit('SPONSOR_MERCHANTS_COOKIES', { // 点击下一步的时候，将当前页的数据保存到cookies
        type: true
      })
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$router.push({path: '/sponsor/merchants/plan'})
        } else {
          this.$message.warning('请输入完整信息')
          return false
        }
      })
    },
    addFormItem () {
      this.form.rightsDetailList.push({
        rightsName: '',
        rightsTypeCode: '',
        exclusiveStatus: 1,
        sponsorType: '',
        investmentAmount: '',
        realPrice: '',
        rightsDetails: []
      })
    },
    show () {
      // console.log(this.form)
    }
  }
}
</script>
<style lang="scss">
.set-box{
  .el-form .input-middle{
    width:520px !important;
  }
  .input-group{
    max-width: inherit;
  }
  .button-box{
    margin-top: 100px;
  }
  .form-style{
    border:1px #e5e5e5 dashed;
    margin:20px 0px;
    padding:40px 0px 20px;
    position:relative;
    .el-select{
      width:100%;
    }
    .set-colse{
      padding-right: 10px;
      margin-top: -35px;
      text-align: right;
      .el-button{
        color:gray;
        font-size:12px;
        padding:0px;
        min-width: 0px;
      }
    }
  }
  .set-button-box{
    text-align: right;
    .el-button{
      margin-right: 0px;
    }
  }
}


</style>
